#include "stdafx.h"
#include "resource.h"

#include "PatternViewerDlg.h"

#include "../nes/nes.h"

#define REFRESH_PATTERN_TIMER 10

BOOL
CPatternViewerDlg::PreTranslateMessage(MSG* pMsg)
{
  return IsDialogMessage(pMsg);
}

LRESULT
CPatternViewerDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/,
                                LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
  CenterWindow(GetParent());
  SetTimer(REFRESH_PATTERN_TIMER, 30);
  return TRUE;
}

void
CPatternViewerDlg::DrawPatternTbl()
{
  if (g_NES && !g_NES->Running()) {
    return;
  }

  u16* image = g_NES->GetPatternImage();

  BITMAPINFO bi = {
    // 1                      2          3           4  5   6  7  8  9  10 11
    sizeof(BITMAPINFOHEADER), PATTERN_W, -PATTERN_H, 1, 16, 0, 0, 0, 0, 0, 0
  };
  RECT rc;
  ::GetClientRect(m_hWnd, &rc);
  HDC hDC = ::GetDC(m_hWnd);
  ::StretchDIBits(hDC, 0, 0, rc.right - rc.left, rc.bottom - rc.top, 0, 0,
                  PATTERN_W, PATTERN_H, image, &bi, DIB_RGB_COLORS,
                  SRCCOPY);
  ::ReleaseDC(m_hWnd, hDC);
}

LRESULT
CPatternViewerDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/,
                           BOOL& /*bHandled*/)
{
  switch (wParam)
  {
    case REFRESH_PATTERN_TIMER:
      DrawPatternTbl();
      break;
  }
  return TRUE;
}

LRESULT
CPatternViewerDlg::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/,
                           LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
  m_IsShow = false;
  ShowWindow(false);
  return FALSE;
}

BOOL
CPatternViewerDlg::ShowHideMe()
{
  m_IsShow = !m_IsShow;
  ShowWindow(m_IsShow);
  if (m_IsShow) {
    SetTimer(REFRESH_PATTERN_TIMER, 30);
  } else {
    KillTimer(REFRESH_PATTERN_TIMER);
  }
  return TRUE;
}
